package com.bootdo.clouddo.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.config.TaskConfig;
import com.bootdo.clouddo.domain.baidu.ImageDO;
import com.bootdo.clouddo.service.baidu.IImageService;
import com.bootdo.clouddo.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class UnsplashTask {

    private static final Logger logger = LoggerFactory.getLogger(UnsplashTask.class);

    private static final String URL = "https://unsplash.com/napi/photos";

    @Autowired
    private IImageService imageService;


    @Async("myExecutor")
    @Scheduled(fixedRate = 6000)
    public void hostSocket() {
        if(!TaskConfig.unsplashTaskRun)
            return;
        Map<String, String> param = new HashMap<>();
        while(true){
            for (int i = 0; i < 4000; i++) {
                param.put("per_page", 30 +"");
                param.put("page", i +"");
                param.put("order_by", "latest");
                try {
                    Thread.sleep(60 * 1000 * 30);
                    int count = getImgInfo(param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private Integer getImgInfo(Map<String, String> param) {
        Integer count = 0;
        try {
            count = getRequest(URL + "?per_page={per_page}&page={page}&order_by={order_by}", param);
        } catch (Exception e) {
            e.getSuppressed();
        }
        return count;
    }

    /**
     * 向目的URL发送get请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
    private Integer getRequest(String url, Map<String, String> params){
        Integer count = 1;
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3000);// 设置超时
        requestFactory.setReadTimeout(3000);
        RestTemplate client = new RestTemplate(requestFactory);
        String re =  client.getForObject(url, String.class,  params);
        if(StringUtils.isNotBlank(re)) {
            JSONArray data = JSONArray.parseArray(re);
            if(data != null) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jo = data.getJSONObject(i);
                    if(jo != null) {
                        ImageDO image = build(jo);
                        if(image != null && image.getId() != null) {
                            try {
                                Thread.sleep(1000);
                                if(imageService.get(image.getId()) == null) {
                                    logger.info("成功拉取到一张图片数据[unsplash]："+JSONObject.toJSONString(image));
                                    imageService.save(image);
                                    count ++;
                                }else {
                                	// System.out.print(".");
                                    //logger.info("发现重复数据[unsplash]:" + image.getId());
                                }
                            }catch (DuplicateKeyException de){
                            	// System.out.print(".");
                                //logger.info("发现重复数据[unsplash]:" + image.getId());
                            }
                            catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return count;
        //return client.getForObject(url, JSONObject.class,  params);
    }

    private ImageDO build(JSONObject obj){
        if(obj== null)
            return null;
        if(obj.getJSONObject("urls") == null)
            return null;
        ImageDO img = new ImageDO();
        img.setSource(ImageDO.TYPE_UNSPLASH);
        img.setId(obj.getString("id"));
        img.setAbs(obj.getString("alt_description"));
        img.setDesc(obj.getString("alt_description"));
        img.setDate(obj.getString("updated_at"));
        img.setImage_height(obj.getDouble("height"));
        img.setImage_width(obj.getDouble("width"));
        img.setLike_num(obj.getInteger("likes"));
        img.setColor(obj.getString("color"));
        JSONObject urls = obj.getJSONObject("urls");
        img.setImage_url(urls.getString("regular"));
        img.setDownload_url(urls.getString("raw"));
        img.setThumb_large_url(urls.getString("small"));
        img.setThumbnail_url(urls.getString("thumb"));

        img.setObj_url(urls.getString("full"));
        img.setOther_urls(JSON.toJSONString(obj.getJSONObject("links")));



        JSONObject user = obj.getJSONObject("user");
        if(user != null){
            img.setUser_id(user.getString("username"));
            img.setHostname(user.getString("portfolio_url"));
            img.setFrom_url(user.getString("portfolio_url"));
            img.setSite_url(user.getString("portfolio_url"));
        }

        return img;
    }

}
